<?php

namespace app\api\controller;

use app\api\validate\TokenGet;
use app\common\BaseHelper;
use app\admin\model\Member;
use app\admin\model\Form;
use app\admin\model\Memberlevel;
use app\admin\model\Membercoupon;
use app\admin\model\Coupon;
use app\api\service\UserToken;
use app\admin\model\Rechargerule;
use app\admin\model\Rechargerecord;
use app\admin\model\MessageNotice;
use app\admin\model\Order;
use app\admin\model\Orderitem;

use app\lib\exception\TokenException;
use think\Db;
use think\Exception;

class User extends Base
{

    /**
     * 获取用户openid
     * @url /token
     * @POST code
     */
    public function getOpenid($code='',$uid='')
    {
        (new TokenGet())->goCheck();
        $wx = new UserToken($code,$uid);
        $openid = $wx->get();
        if($openid){
            return show(config('status.SUCCESS_STATUS'), 'ok', $openid);
        }else{
            return show(config('status.ERROR_STATUS'), 'error', 'error');
        }
    }

    /**
     * 第三方应用获取令牌
     * @url /app_token?
     * @POST ac=:ac se=:secret
     */
    public function getAppToken($ac='', $se='')
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET');
        (new AppTokenGet())->goCheck();
        $app = new AppToken();
        $token = $app->get($ac, $se);
        return [
            'token' => $token
        ];
    }

    public function saveToken(){
        $key = \app\api\service\Token::generateToken();
        $value = config('token.ApiKey');
        $expire_in = config('token.token_expire_in');
        $request = cache($key,$value,$expire_in);
        if(!$request){
            throw new TokenException([
                'msg' => '服务器缓存异常',
                'errorCode' => 10005
            ]);
        }
        return $key;
    }

    /**
     * 个人中心页面
     */
    public function userHome()
    {
        $param = self::getHttpParam();

        $countOrder = [];
        if (!empty($param->memberId)) {
            $memberId = $param->memberId;
            // 待付款
            $countPendingPay = Order::where(['member_id' => $memberId, 'status' => 1])->count();
            // 待配送
            //$countDelivery = Order::where(['member_id' => $memberId, 'status' => ['in', '2,3']])->count();
            // 备货中
            $countInStocking = Order::where(['member_id' => $memberId, 'status' => 2])->count();
            // 配送中
            $countInDelivery = Order::where(['member_id' => $memberId, 'status' => 3])->count();
            // 待自提
            $countPending = Order::where(['member_id' => $memberId, 'status' => 6])->count();
            // 待评价
            //$orderIds = Order::where(['member_id' => $memberId, 'status' => ['not in', [1,5]]])->column('id');
            $orderIds = Order::where(['member_id' => $memberId, 'status' => 4])->column('id');
            $countComment = Orderitem::where(['order_id' => ['in', $orderIds], 'is_comment' => 0])->count();
            // 售后/退款
            $countRefund = Order::where(['member_id' => $memberId, 'status' => 9])->count();

            $countOrder = [
                'countPendingPay' => $countPendingPay,
                //'countDelivery' => $countDelivery,
                'countInStocking' => $countInStocking,
                'countInDelivery' => $countInDelivery,
                'countPending' => $countPending,
                'countComment' => $countComment,
                'countRefund' => $countRefund,
            ];
        }

        $data = [
            'countOrder' => $countOrder,
            // 背景图
            'level1_bg' => 'https://' . $_SERVER['HTTP_HOST'] . '/public/static/wechat/image/invitation.png',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 登录&注册
     *
     * @return \think\Response
     */
    public function login()
    {
        $param = self::getHttpParam();
        if (empty($param->phone)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '手机号不能为空');
        }

        $model = new Member();
        $member = $model->where('account_number', $param->phone)->find();
        if (empty($member) || !$member) {
            // 注册
            Db::startTrans();
            try {
                $data = [
                    'id' => BaseHelper::getUUID22(),
                    'account_number' => $param->phone,
                    'status' => 1,
                    'create_date' => date('Y-m-d H:i:s',time()),
                    'member_level_id' => 1, // 默认为普通会员
                    'level_open_time' => date('Y-m-d H:i:s',time()),
                ];
                if (!empty($param->cid)) {
                    $data['c_id'] = $param->cid;
                }
                // 分享邀请只对新用户有效
                if (!empty($param->chiefUserAccount)) {
                    // 分享者信息
                    //$sharerInfo = $model->where('account_number', $param->sharerPhone)->field('id, account_number')->find();
                    $data['chief_user_account'] = $param->chiefUserAccount;
                }

                $result = $model->save($data);
                if ($result !== false) {
                    // 默认开通普通会员
                    $memberlevelInfo = Memberlevel::where('id', 1)->field('name, img_url, is_coupon, coupon_ids')->find();
                    // 新用户获得优惠券
                    if ($memberlevelInfo['is_coupon'] == 1) {
                        $couponIds = Coupon::where(['id' => ['in', $memberlevelInfo['coupon_ids']], 'coupon_purpose' => 1, 'end_time' => ['gt', date('Y-m-d H:i:s')]])->column('id');
                        if ($couponIds) {
                            foreach ($couponIds as $couponId) {
                                $couponData = [
                                    'id' => BaseHelper::getUUID(),
                                    'create_date' => date('Y-m-d H:i:s'),
                                    'member_id' => $data['id'],
                                    'coupon_id' => $couponId
                                ];

                                $couponRes = Membercoupon::insert($couponData);
                                if($couponRes === false){
                                    Db::rollback();
                                    return ['code' => 0, 'msg' => '开通会员赠送优惠券失败'];
                                }
                            }
                            // 添加账户通知消息 -- 获得优惠券
                            $couponMesData = [
                                'create_date' => date('Y-m-d H:i:s'),
                                'member_id' => $data['id'],
                                'img_url' => '',
                                'title' => '您获得了优惠券',
                                'detail' => '您获得了' . count($couponIds) . '张优惠券，点击立即使用',
                                'type' => 1
                            ];
                            $couponMesRes = MessageNotice::insert($couponMesData);
                            if($couponMesRes === false){
                                Db::rollback();
                                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '添加优惠券账户通知消息失败');
                            }
                        }
                    }

                    $member = $model->get($data['id']);
                    // 获取用户详细信息
                    $member = $this->getMemberInfo($member);

//                    $key = \app\api\service\Token::generateToken();
//                    $cahe['uid'] = $data['id'];
//                    $value = json_encode($cahe);
//                    $expire_in = config('token.token_expire_in');
//                    $result = cache($key, $value, $expire_in);

                    // 是否是邀请注册
                    if (!empty($param->chiefUserAccount)) {
                        $invitation = \app\admin\model\Invitation::field('member_coupon_id, invitation_coupon_id')->find();
                        // 新用户获得优惠券
                        $shareCouponData = [
                            'id' => BaseHelper::getUUID(),
                            'create_date' => date('Y-m-d H:i:s'),
                            'member_id' => $data['id'],
                            'coupon_id' => $invitation['member_coupon_id']
                        ];

                        $shareCouponRes = Membercoupon::insert($shareCouponData);
                        if($shareCouponRes === false){
                            Db::rollback();
                            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '赠送优惠券失败');
                        }
                        // TODO 新用户注册成功，给分享者送优惠券（要下单签收才可以）

                        $member['message'] = '您已成功领取优惠券';
                    }

                    Db::commit();
                    return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $member);
                } else {
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
            }
        } else {
            // 登录
            if ($member['m_status'] != 1) {
                return show(config('status.ERROR_STATUS'), '此账号已被禁用或被删除', '此账号已被禁用或被删除');
            }

            if (!empty($param->formId)) {
                $formMdl = new Form();
                $data = [
                    'id' => $param->formId,
                    'phone' => $param->phone,
                    'create_date' => date('Y-m-d H:i:s',time()),
                ];
                $result = $formMdl->save($data);
                if (!$result){
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
                }
            }
            if (!empty($param->cid)) {
                // App 唯一标识会根据不同手机而改变，故每次登录需要更新
                $sql = $model->where('account_number', $param->phone)->update(['c_id' => $param->cid]);
                if ($sql === false){
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
                }
            }
            // 获取用户详细信息
            $member = $this->getMemberInfo($member);

            $member['phone'] = substr($member['account_number'], 0, 3).'****'.substr($member['account_number'], 7);

            $member['birthday'] = substr($member['birthday'],0,10);
            $member['message'] = '';

            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $member);
        }
    }

    /**
     * 个人资料
     */
    public function userInfo(){
        $param = self::getHttpParam();

        if (empty($param->phone)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'phone 不能为空');
        }

        $account_number = $param->phone;
        $where = [
            'account_number' => $account_number,
        ];

        $item = Member::where($where)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), '未查到个人资料', '未查到个人资料');
        }
        $item['phone'] = substr($item['account_number'], 0, 3).'****'.substr($item['account_number'], 7);
        $item = $this->getMemberInfo($item);
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存个人资料
     */
    public function saveUser()
    {
        $param = self::getHttpParam();

        if (empty($param->avatar)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'avatar不能为空');
        }
        if (empty($param->phone)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'phone不能为空');
        }
        if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'name不能为空');
        }
        if (empty($param->sex)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'sex不能为空');
        }
        if (empty($param->birthday)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'birthday不能为空');
        }

        $result = Member::update($param,['account_number'=>$param->phone],true);

        if (!$result){
            return show(config('status.ERROR_STATUS'), '保存失败', '保存失败');
        }

        $account_number = $param->phone;
        $where = [
            'account_number' => $account_number,
        ];
        $member = Member::where($where)->find();

        if ((int)$member['is_one_create'] == 1){
            $perfect_info = db('integral_rule')->field('perfect_info')->find();
            $data = [
                'is_one_create' => 2,
                'integral' => (int)$member['integral'] + (int)$perfect_info['perfect_info']
            ];

            $result = Member::update($data,['account_number'=>$param->phone],true);
            if ($result !== false) {
                $record_data =[
                    'member_id' => $member['id'],
                    'type' => 1,
                    'source' =>'完善个人资料',
                    'exchange_num' => $perfect_info['perfect_info']
                ];
                \app\admin\model\Integralrecord::create($record_data);

                $member['integral'] = $data['integral'];
            }
        }

        if (empty($member)) {
            return show(config('status.ERROR_STATUS'), '未查到个人资料', '未查到个人资料');
        }
        $member = $this->getMemberInfo($member);
        $member['phone'] = substr($member['account_number'], 0, 3).'****'.substr($member['account_number'], 7);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $member);
    }

    /*
     * 优惠券
     * */
    public function coupon()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 10;
        if (!empty($param->start)){
            $start = $param->start;
        }
        if (!empty($param->length)){
            $start = $param->length;
        }
        if (empty($param->id)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id不能为空');
        }
        if (empty($param->type)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type不能为空');
        }
        $time = date('Y-m-d H:i:s',time());
        if ($param->type == 1){
            $where = [
                'm.member_id' => $param->id,
                'a.end_time' => ['gt',$time],
                'm.status'   => 1,
                'a.status'   => 1
            ];
        }
        if ($param->type == 2){
            $where = [
                'm.member_id' => $param->id,
                'm.status'   => 2
            ];
        }
        if ($param->type == 3){
            $where = [
                'm.member_id' => $param->id,
                'a.end_time' => ['lt',$time],
            ];
        }
        $couponMdl = new Coupon();
        $result = $couponMdl->alias('a')
            ->join('member_coupon m','a.id = m.coupon_id')
            ->where($where)
            ->limit($start,$length)
            ->select();

        if (!$result){
            return show(config('status.ERROR_STATUS'), '未查到优惠券', '未查到优惠券');
        }

        //获得优惠券类型
        foreach($result as $v)
        {
            $v['coupon_type'] = show_coupon_type($v['coupon_type']);
            $v['coupon_purpose'] = show_coupon_purpose($v['coupon_purpose']);
        }
        $total = count($result);

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }
    //我的钱包
    public function wallet()
    {
        $param = self::getHttpParam();
        $model = new Member();
        if (empty($param->memberId)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId不能为空');
        }

        $result = $model->alias('a')
            ->where(['a.id'=>$param->memberId])
            ->join('member_level m','a.member_level_id = m.id')
            ->field('a.id,balance,m.recharge_rule_id')
            ->find();

        if (!$result){
            return show(config('status.ERROR_STATUS'), '未查到余额信息', '未查到余额信息');
        }
        $rechargeRuleMdl = new Rechargerule();
        $rule = $rechargeRuleMdl->where(['id'=>$result['recharge_rule_id']])->find();
        $rule = json_decode($rule['rule_json']);
        $result['recharge_rule'] = $rule;
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    //钱包消费/充值 明细
    public function walletDetail()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;
        if (!empty($param->start)){
            $start = $param->start;
        }
        if (!empty($param->length)){
            $length = $param->length;
        }
        $model = new Rechargerecord();
        if (empty($param->memberId)){
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId不能为空');
        }
        $data = $model->where(['member_id' => $param->memberId, 'status' => ['neq', 0]])->limit($start,$length)->order('create_date Desc')->select();
        if (!$data){
            return show(config('status.ERROR_STATUS'), '没有明细信息', '没有明细信息');
        }
        $res = [];
        //得到月份
        foreach ((array)$data as $item) {
            $date         = substr($item['create_date'], 0, 7);
            $res[]['create_date'] = $date;
        }
        //去重
        (array)$result = array_unique($res, SORT_REGULAR);
        $arr = [];
        foreach($result as $v){
           $arr[] = $v;
        }
        foreach($data as $item){
            if ($item['type'] == 1){
                $item['record_money'] = $item['record_money'] + $item['gift_money'];
            }
            foreach($arr as &$v){
                $date = substr($item['create_date'], 0, 7);
                if ($date == $v['create_date']){
                    $item['record_money'] = sprintf("%.2f",$item['record_money']/100);
                    if (!empty($item['gift_money'])){
                        $item['gift_money'] = sprintf("%.2f",$item['gift_money'] /100);
                    }
                    $v['detail'][] = $item;
                }
            }
        }
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $arr);
    }
}
